import 'rxjs/add/operator/switchMap';

import { Component, Input, OnInit, HostBinding } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { Location } from '@angular/common';

import { slideInDownAnimation } from '../../animations';

import { HeroService } from '../shared/hero.service';
import { Hero } from '../shared/hero.model';


@Component({
  selector: 'hero-detail',
  template: `
    <div *ngIf="hero">
      <h2>{{hero.name}} details!</h2>
      <div><label>id: </label>{{hero.id}}</div>
      <div>
        <label>name: </label>
        <input [(ngModel)]="hero.name" placeholder="name"/>
      </div>
      <button (click)="goBack()">Back</button>
      <button (click)="save()">Save</button>
    </div>
  `,
  styleUrls: ['./hero-detail.component.css'],
  animations: [ slideInDownAnimation ]
})

export class HeroDetailComponent implements OnInit {

  @HostBinding('@routeAnimation') routeAnimation = true;
  @HostBinding('style.display') display = 'block';
  @HostBinding('style.position') position = 'absolute';

  // 单个英雄
  @Input() hero: Hero;

  constructor(
    private heroService: HeroService,
    private route: ActivatedRoute,
    private router: Router,
    private location: Location
  ) {

  }


  /**
   * 初始化
   */
  ngOnInit(): void {
    this.route.params
      .switchMap((params: Params) => this.heroService.getHero(+params['id']))
      .subscribe(hero => this.hero = hero); // 检测id的变化

    // Snapshot（快照）：当不需要Observable时的替代品
    // let id = +this.route.snapshot.params['id'];
    // this.heroService.getHero(id)
    //   .then((hero: Hero) => this.hero = hero);
  }
  /**
   * 修改英雄
   */
  save(): void {
    this.heroService.update(this.hero)
      .then(() => this.goBack());
  }
  /**
   * 返回上一页
   */
  goBack(): void {
    // this.location.back();

    let heroId = this.hero ? this.hero.id : null;
    this.router.navigate(['/heroes', { id: heroId, foo: 'foo' }]);
  }
}